var utilMd5 = require('md5.js');
var Promise = require('../utils/es6-promise.js')

function wxPromisify(fn) {
    return function(obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function(res) {
                //成功
                resolve(res)
            }
            obj.fail = function(res) {
                //失败
                reject(res)
                wx.showModal({
                    title: wx.getStorageSync("isChinese") ? '提示' : "Prompt",
                    showCancel: false,
                    content: wx.getStorageSync("isChinese") ? "网络连接超时" : "Request timed out"
                })
                return;
            }
            fn(obj)
        })
    }
}
//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function(callback) {
    let P = this.constructor;
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason => P.resolve(callback()).then(() => { throw reason })
    );
};
/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data) {
    var getRequest = wxPromisify(wx.request)
    return getRequest({
        url: url,
        method: 'GET',
        data: data,
        header: {
            'Content-Type': 'application/json'
        }
    })
}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(method, data, s_url) {
    var postRequest = wxPromisify(wx.request)
    let url = s_url ? 'https://a.onepartygo.com/event/api.do' : "https://a.onepartygo.com/router"
    return postRequest({
        url: url,
        method: method,
        data: data,
        header: {
            "content-type": "application/x-www-form-urlencoded"
        },
    })
}

function getUuid(method, data) {
    data.format = 'json'
    data.locale = "zh_CN"
    data.sign_method = "md5"
    data.app_key = '0617CA8376F9901F28FF46B69BF9CF55'
    data.timestamp = Date.parse(new Date());
    data.v = "1.0"
    data = this.objKeySort(data)
    var md = this.getSign(data)
    data.sign = md
    return this.postRequest(method, data)
}

function getNsProducts(method, data) {
    data.format = 'json'
    data.locale = "zh_CN"
    data.sign_method = "md5"
        // data.account = "86-13585506509"
    data.app_key = '0617CA8376F9901F28FF46B69BF9CF55'
    data.timestamp = Date.parse(new Date());
    // data.timestamp = "1499936931714"
    data.v = "1.0"
        // data.password = '7694f4a66316e53c8cdd9d9954bd611d'
    data = this.objKeySort(data)
    var md = this.getSign(data)
    data.sign = md
    return this.postRequest(method, data)
}

function getProducts(method, data, s_url = false) {
    if (this.session == '') {
        wx.showModal({
            title: wx.getStorageSync("isChinese") ? '提示' : "Prompt",
            showCancel: false,
            content: "请点击右上角... -关于设置- ... -设置-用户信息中设置"
        })
        return;
    }
    data.format = 'json'
    data.locale = "zh_CN"
    data.sign_method = "md5"
        // data.account = "86-13585506509"
    data.app_key = '0617CA8376F9901F28FF46B69BF9CF55'
    data.timestamp = Date.parse(new Date());
    // data.timestamp = "1499936931714"
    data.session = this.session
    data.v = "1.0"
        // data.password = '7694f4a66316e53c8cdd9d9954bd611d'
    data = this.objKeySort(data)
    var md = this.getSign(data)
    data.sign = md
    return this.postRequest(method, data, s_url)
}

function getSign(data) { //编译getSign
    let app_key = '';
    Object.keys(data).forEach((item, index) => {
        app_key = app_key + item + data[item]
    })

    app_key = "28570C9D069ED51226DD9F028BD5E6EE" + app_key + "28570C9D069ED51226DD9F028BD5E6EE"
    return utilMd5.hexMD5(app_key)
}

function objKeySort(obj) { //排序的函数
    var newkey = Object.keys(obj).sort();　　 //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
    for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
        newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newObj; //返回排好序的新对象
}
module.exports = {
    getProducts: getProducts,
    getUuid: getUuid,
    session: "",
    getSign: getSign,
    objKeySort: objKeySort,
    postRequest: postRequest,
    getNsProducts: getNsProducts
}